<template>
<div class="category-container">
    <el-card class="category-card" shadow="never">
        <!-- 顶部操作栏 -->
        <div class="operation-bar">
            <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>添加分类
            </el-button>
            <el-input
                v-model="searchKeyword"
                placeholder="请输入分类名称搜索"
                class="search-input"
                clearable
            >
                <template #prefix>
                    <el-icon><Search /></el-icon>
                </template>
            </el-input>
        </div>

        <!-- 分类表格 -->
        <el-table
            :data="filteredCategories"
            row-key="id"
            border
            stripe
            style="width: 100%"
            height="calc(100vh - 280px)"
            :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 600,
                height: '50px'
            }"
        >
            <el-table-column prop="name" label="分类名称" min-width="200">
                <template #default="{ row }">
                    <div class="category-name">
                        <el-image :src="row.image" fit="cover" class="product-image" />
                        <span>{{ row.name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述">
                <template #default="{ row }">
                    <span>{{ row.description }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="productCount" label="商品数量" width="120" align="center">
                <template #default="{ row }">
                    <el-tag 
                        :type="row.productCount > 0 ? 'success' : 'info'" 
                        round
                        effect="plain"
                        size="large"
                    >
                        {{ row.productCount }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" align="center">
                <template #default="{ row }">
                    <el-switch
                        v-model="row.status"
                        @change="CategoryApi.updateById(row, row.id)"
                        :active-text="row.status ? '已启用' : ''"
                        :inactive-text="row.status ? '' : '已禁用'"
                        inline-prompt
                        style="--el-switch-on-color: #13ce66"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button-group class="operation-group">
                    <el-tooltip content="编辑" placement="top">
                        <el-button type="primary" link @click="handleEdit(row)">
                        <el-icon><Edit /></el-icon>
                        </el-button>
                    </el-tooltip>
                    <el-tooltip :content="row.productCount > 0 ? '该分类下有商品，不能删除' : '删除'" placement="top">
                        <el-button 
                            type="danger" 
                            link 
                            @click="handleDelete(row)"
                            :disabled="row.productCount > 0"
                        >
                        <el-icon><Delete /></el-icon>
                        </el-button>
                    </el-tooltip>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
</div>

<!-- 添加/编辑窗口 -->
<el-dialog
  :title="isEdit ? '编辑' : '新增'"
  v-model="dialogVisible"
  width="600px"
  destroy-on-close
  align-center
  @close="handleDialogClose"
>
    <el-form
        ref="formRef"
        :model="form"
        :rules="categoryFormRules"
        label-width="100px"
        class="category-form"
    >
        <el-form-item label="分类名称" prop="name">
            <el-input 
                v-model="form.name" 
                placeholder="请输入分类名称"
                maxlength="20"
                show-word-limit
            />
        </el-form-item>
        <el-form-item label="描述" prop="description">
            <el-input 
                v-model="form.description" 
                placeholder="请输入描述"
                maxlength="20"
                show-word-limit
            />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
        <img v-if="isEdit && showImage" :src="backImage" width="150px" style="margin-right: 20px;"/>
        <el-upload 
            ref="upload"
            action="#" 
            list-type="picture-card" 
            :auto-upload="false" 
            :multiple="false" 
            :limit="1"
            :on-change="handleOnChange"
            :on-exceed="handleOnExceed">
          <el-icon>
            <Plus />
          </el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
        <el-form-item label="状态">
            <el-switch 
                v-model="form.status"
                :active-text="form.status ? '启用' : ''"
                :inactive-text="form.status ? '' : '禁用'"
                inline-prompt
                style="--el-switch-on-color: #13ce66"
            />
        </el-form-item>
    </el-form>
    <template #footer>
        <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
    </template>
</el-dialog>
</template>

<script setup lang="ts">
import { Category, CategoryApi, CategoryForm, categoryFormRules, getInitCategoryForm } from '@/models/categoryModel';
import { onMounted, ref, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, UploadFile, UploadFiles, UploadUserFile } from 'element-plus'

// 搜索数据
const searchKeyword = ref<string>('')
// 显示编辑/新增窗口
const dialogVisible = ref<boolean>(false)
// 校验表单数据
const formRef = ref<FormInstance>()
// 表单提交数据
const form = ref<CategoryForm>(getInitCategoryForm())

// 是否显示图片（在编辑商品时，显示商品原图片）
const showImage = ref<boolean>(true)
const backImage = ref()
const disabled = ref(false)     // 是否显示删除图片按钮
const upload = ref()            // 上传图片组件

// 编辑/新增
const isEdit = ref<boolean>(false)

// 分类数据
const categories = ref<Category[]>([])

// 符合条件的分类数据
const filteredCategories = computed(() => {
    if (!searchKeyword.value) return categories.value
    return categories.value.filter(item => 
        item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
})

onMounted(() => {
    // 请求数据
    CategoryApi.getAll()
    .then(data => {
        categories.value = data        
    })
})

// 打开编辑窗口
const handleEdit = (row: Category) => {
  isEdit.value = true
  form.value = {...row}
  dialogVisible.value = true
  showImage.value = true
  backImage.value = row.image
}

// 新增数据
const handleAdd = () => {
  showImage.value = false
  isEdit.value = false
  form.value = getInitCategoryForm()
  dialogVisible.value = true
}

// 是否删除
const handleDelete = (row: Category) => {
    if (row.productCount > 0) {
        ElMessage.warning('该分类下还有商品，不能删除')
        return
    }
    ElMessageBox.confirm('确定要删除该分类吗？', '警告')
    .then(() => {
        // 这里应该调用删除API
        CategoryApi.deleteById(row.id)
        .then(() => {
            categories.value = categories.value.filter(item => item.id != row.id)
        })
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      if (!isEdit.value) {
        // 添加
        CategoryApi.create(form.value)
        .then(data => {
          categories.value.push(data)
          dialogVisible.value = false
        })
      }
      else {
        // 修改
        CategoryApi.updateById(form.value, form.value.id)
        .then(data => {
          const index = categories.value.findIndex(item => item.id == data.id)
          categories.value[index] = data
          dialogVisible.value = false
        })
      }
    }
  })
}

// 关闭 新增/编辑商品 窗口时
const handleDialogClose = () => {
    upload.value!.clearFiles()
    showImage.value = false
}

// 当选择了一个图片
const handleOnChange = (uploadfile: UploadFile, uploadFiles: UploadFiles) => {
    form.value.image = uploadfile.raw
    // 不是编辑状态，不显示商品原图
    if (isEdit) showImage.value = false
}

// 重复选择图片时
const handleOnExceed = (files: File[], uploadFiles: UploadUserFile[]) => {
  ElMessage.error("图片已经选择!")
}

// 删除选中图片
const handleRemove = (file: UploadFile) => {
  upload.value!.clearFiles()
  if (isEdit) {
    showImage.value = true
    form.value.image = backImage.value
  }
}
</script>

<style scoped>
.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.category-container {
  height: 100%;
}

.category-card {
  height: 100%;
  border-radius: 8px;
}

.operation-bar {
  padding: 16px 0;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-card__body) {
  height: calc(100% - 20px);
  display: flex;
  flex-direction: column;
  padding: 16px;
}

:deep(.el-table) {
  flex: 1;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}

.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.folder-icon {
  color: #909399;
  font-size: 18px;
}

.operation-group {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.operation-group .el-button {
  font-size: 16px;
  padding: 4px;
}

:deep(.el-switch__label) {
  font-size: 12px;
}

:deep(.el-tag) {
  min-width: 60px;
  height: 28px;
  font-size: 14px;
}

.category-form {
  padding: 20px 40px;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  border-radius: 3px;
  background: #dcdfe6;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  border-radius: 3px;
  background: #f5f7fa;
}
</style> 